package com.atguigu.gulimall.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean sendCode(String phone) {
        String smsRedisKey = AuthServerConstant.LOGIN_CODE_KEY + phone;
        // 防止60s内再次发送验证码
        String redisCode = redisTemplate.opsForValue().get(smsRedisKey);
        if (StringUtils.hasText(redisCode)) {
            long setTime = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - setTime < 60*1000) {
                // 60s内不能重复发送验证码
                return false;
            }
        }
        // 生成验证码
        String code = RandomUtil.randomNumbers(5);
        System.out.println("code：" + code);
        // 保存验证码到redis，设置有效时间为五分钟
        String smsRedisValue = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(smsRedisKey, smsRedisValue, AuthServerConstant.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // 发送验证码
//        thirdPartFeignService.sendCode(phone, code);
        return true;
    }

    @Override
    public boolean checkCode(String phone, String code) {
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.LOGIN_CODE_KEY + phone);
        if (StringUtils.hasText(redisCode) && code.equals(redisCode.split("_")[0])) {
            // 验证码输入正确，删除验证码
            redisTemplate.delete(AuthServerConstant.LOGIN_CODE_KEY + phone);
            return true;
        } else {
            // 验证码过期或验证码输入有误，重新输入
            return false;
        }
    }
}
